"use strict";

const Controller = require("egg").Controller;
const path = require("path");
class UserController extends Controller {
  async registry() {
    // 解析服务端
    const { service } = this.ctx;
    // 接收前端传参
    let body = this.ctx.request.body;
    const { emali, password, fileimg } = body;

    // 非空验证
    if (emali && password && fileimg) {
      const errors = app.validator.validate(
        { emali: "emali", password: "password", fileimg: "fileimg" },
        ctx.request.body
      );
      if (errors) {
        this.ctx.body = {
          code: "FALI",
          msg: "输入参数不合规范",
          status: 417,
        };
      } else {
        // 调用服务端查找功能
        const findres = await service.user.find(body);

        // 判断是否存在
        if (!findres) {
          // 调用服务端注册功能
          await service.user.registry(body);
          this.ctx.body = {
            code: "SUCCESS",
            msg: "注册成功",
            status: 200,
          };
        } else {
          this.ctx.body = {
            code: "FIAL",
            msg: "该用户已存在，请前往登录",
            status: 417,
          };
        }
      }
    } else {
      this.ctx.body = {
        code: "FIAL",
        msg: "注册信息不能为空",
        status: 417,
      };
    }
  }
  async login() {
    // 解析服务端
    const { service } = this.ctx;
    // 接收前端传参
    let body = this.ctx.request.body;
    const { emali, password } = body;

    // 非空验证
    if (emali && password) {
      const errors = app.validator.validate(
        { emali: "emali", password: "password" },
        ctx.request.body
      );
      if (errors) {
        this.ctx.body = {
          code: "FALI",
          msg: "输入参数不合规范",
          status: 417,
        };
      } else {
        // 调用服务端登录功能
        await service.user.login(body);
        this.ctx.body = {
          code: "SUCCESS",
          msg: "登录成功",
          status: 200,
        };
      }
    } else {
      this.ctx.body = {
        code: "FIAL",
        msg: "登录信息不能为空",
        status: 417,
      };
    }
  }
  async uphead(ctx) {
    // 接收前端传参
    const [ file ] = ctx.request.files;
    // 拼接路径
    const name = path.join(__dirname, '../public/images', file.filename);
    try {
      // 第一个参数是目标文件,第二个参数是原文件
      await ctx.put(name, file.filepath);
    } catch (error) {
      this.ctx.body = {
        code: 500,
        msg: "服务器错误",
      };
      return;
    }
    this.ctx.body = {
      code: 200,
      msg: "图片上传成功",
      url: "../public/images" + file.filename,
    };
  }
}

module.exports = UserController;
